from sqlalchemy.orm import Session
from app.db.models import TLabel, TCategory, TMiddlePostLabel, TPost  # 假设这些是表对应的模型
from app.db.crud import create_tjudge, update_tpost_is_judge
class TagSaver:
    def __init__(self, db: Session, post_id: int, tags: list[str], categorys: list[str], reason: str, stars: str):
        self.db = db
        self.post_id = post_id
        self.tags = tags
        self.categorys = categorys
        self.reason = reason
        self.stars = stars

    def save(self):
        """保存标签、分类和原因"""
        self._save_tags()
        self._save_category()
        self._save_reason()
        success = update_tpost_is_judge(self.db, self.post_id, True)

    def _save_tags(self):
        """保存标签并建立与文章的关联关系"""
        for tag_name in self.tags:
            # 检查标签是否已存在
            tag = self.db.query(TLabel).filter(TLabel.ch_name == tag_name).first()
            if not tag:
                # 标签不存在，创建新标签
                tag = TLabel(name=tag_name, ch_name=tag_name, delete_flag=0)
                self.db.add(tag)
                self.db.commit()
                self.db.refresh(tag)

            # 检查关联关系是否已存在
            existing_link = self.db.query(TMiddlePostLabel).filter(
                TMiddlePostLabel.post_id == self.post_id,
                TMiddlePostLabel.label_id == tag.id,
                TMiddlePostLabel.delete_flag == 0
            ).first()
            if not existing_link:
                # 创建关联关系
                link = TMiddlePostLabel(post_id=self.post_id, label_id=tag.id, delete_flag=0)
                self.db.add(link)
                self.db.commit()

    def _save_category(self):
        """保存分类并更新文章的分类字段"""
        for category_name in self.categorys:
            # 检查分类是否已存在
            category = self.db.query(TCategory).filter(TCategory.name == category_name).first()
            if not category:
                # 分类不存在，创建新分类
                category = TCategory(name=category_name,delete_flag=0)
                self.db.add(category)
                self.db.commit()
                self.db.refresh(category)

            # 更新文章的分类字段
            post = self.db.query(TPost).filter(TPost.id == self.post_id).first()
            if post:
                post.category_id = category.id
                self.db.commit()

    def _save_reason(self):
        """保存原因"""
        if self.reason:
            post = self.db.query(TPost).filter(TPost.id == self.post_id).first()
            if post:
                post.short_content = self.reason  # 假设 post 表有一个 reason 字段
                post.stars = self.stars
                self.db.commit()